// 监听工作类型输入框
const jobTypeInput = document.getElementById('jobTypeInput');
jobTypeInput.addEventListener('input', function () {
    const value = this.value.trim().toLowerCase();
    if (value === '互联网开发' || value === '软件开发') {
        openModal('jobTypeModal');
    }
});

// 监听工作类型输入框
const WorkCity = document.getElementById('workCity');
workCity.addEventListener('input', function () {
    const value = this.value.trim().toLowerCase();
    // if (value === '互联网开发' || value === '软件开发') {
    //     openModal('jobTypeModal');
    // }
});

// 监听 MySQL 选择
document.getElementById('mysqlYes').addEventListener('change', function () {
    if (this.checked) openModal('mysqlModal');
});
document.getElementById('mysqlNo').addEventListener('change', function () {
    if (this.checked) {
        document.getElementById('mysqlInfoDisplay').classList.add('hidden');
        document.getElementById('mysqlInfo').textContent = '';
    }
});

// 监听 Redis 选择
document.getElementById('redisYes').addEventListener('change', function () {
    if (this.checked) openModal('redisModal');
});
document.getElementById('redisNo').addEventListener('change', function () {
    if (this.checked) {
        document.getElementById('redisInfoDisplay').classList.add('hidden');
        document.getElementById('redisInfo').textContent = '';
    }
});

// 打开弹窗
function openModal(modalId) {
    document.getElementById(modalId).style.display = 'block';
    document.getElementById('overlay').style.display = 'block';
}

// 关闭弹窗
function closeModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
    document.getElementById('overlay').style.display = 'none';
}

// 保存技术栈并显示在页面上
function saveTechStack() {
    document.getElementById('selectedTechStack').textContent = document.getElementById('techStackSelect').value;
    document.getElementById('techStackDisplay').classList.remove('hidden');
    closeModal('jobTypeModal');
}

// 保存 MySQL 信息并显示在页面上
function saveMySQLInfo() {
    const host = document.getElementById('mysqlHost').value;
    const user = document.getElementById('mysqlUser').value;
    const password = document.getElementById('mysqlPassword').value;
    document.getElementById('mysqlInfo').textContent = `主机: ${host}, 用户名: ${user}, 密码: ${password}`;
    // document.getElementById('mysqlInfoDisplay').classList.remove('hidden');
    closeModal('mysqlModal');
}

// 保存 Redis 信息并显示在页面上
function saveRedisInfo() {
    const host = document.getElementById('redisHost').value;
    const port = document.getElementById('redisPort').value;
    const password = document.getElementById('redisPassword').value;
    document.getElementById('redisInfo').textContent = `主机: ${host}, 端口: ${port}, 密码: ${password}`;
    // document.getElementById('redisInfoDisplay').classList.remove('hidden');
    closeModal('redisModal');
}

// 表单提交
document.getElementById('taskForm').addEventListener('submit', function (event) {
    event.preventDefault();
    var workType = jobTypeInput.value;
    const workCity = WorkCity.value;
    const techStack = document.getElementById('selectedTechStack').textContent;
    if (techStack !== "") {
        workType = techStack
    }

    const useMysqlRedis = "否"
    // alert(`任务已提交！\n工作类型：${jobType}\n技术栈：${techStack}\nMySQL 信息：${mysqlInfo}\nRedis 信息：${redisInfo}`);
    // 这里可以添加提交表单的逻辑
    sendRequest("/auth/api/v1/city_work", {workType, workCity, useMysqlRedis}, "POST", (data) => success(data, "/task/list"), (error) => errFail(error))
});

// 发送 AJAX 请求
function sendRequest(url, data, method, successCallback, errorCallback) {
    let allCookies = document.cookie; // 从 localStorage 获取 token

    const headers = {
        "Content-Type": "application/json",
    };
    // 如果 token 和 userId 存在，添加到请求头
    if (allCookies) {
        headers["Cookie"] = allCookies;
    }
    $.ajax({
        url: url,
        data: JSON.stringify(data),
        type: method,
        headers: headers, // 设置自定义请求头
        success: successCallback,
        error: errorCallback,
    });
}

//成功
function success(data, url) {
    if (data.code===1&&data.message === "数据存在,可直接查看"){
        showError(data.message,'/jobs');
        return
    }
    // console.log("页面加载完成5", "/welcome");
    if (data.code === 1 || data.message !== "数据需重新采集，请等待") {
        showError(data.message,"");
    } else {
        showError(data.message);
    }
}

//失败
function errFail(data) {
    showError(data.message);
}

// 显示美观的错误对话框（带跳转链接）
function showError(message, url) {
    const errorMsg = document.getElementById('errorMsg');
    if (url!==""){
        // 构建带样式的消息内容
        errorMsg.innerHTML = `
        <div class="error-content">
            <p>${message}</p>
            <a href="${url}" target="_blank" class="jump-link">点击此处查看数据 →</a>
        </div>
    `;
    }else {
        // 构建带样式的消息内容
        errorMsg.innerHTML = `
        <div class="error-content">
            <p>${message}</p>
<!--            <a href="${url}" target="_blank" class="jump-link">点击此处查看数据 →</a>-->
        </div>
    `;
    }
// 所有DOM操作代码放在这里
    console.log("页面加载完成", "/welcome");
    // 显示对话框和遮罩
    document.getElementById('errorDialog').style.display = 'block';
    document.getElementById('overlay').style.display = 'block';

    // 阻止背景滚动
    document.body.style.overflow = 'hidden';
}

// 隐藏对话框
function hideError() {
    document.getElementById('errorDialog').style.display = 'none';
    document.getElementById('overlay').style.display = 'none';
    document.body.style.overflow = 'auto';
}

// 页面加载后初始化事件
document.addEventListener('DOMContentLoaded', function() {
    // 绑定关闭按钮事件
    document.getElementById('closeButton').addEventListener('click', hideError);
    document.getElementById('closeButton01').addEventListener('click', hideError);

    // 点击遮罩层也可以关闭
    document.getElementById('overlay').addEventListener('click', hideError);
// 所有DOM操作代码放在这里
//     console.log("页面加载完成1", "/welcome");
    // 阻止对话框内部点击事件冒泡
    document.getElementById('errorDialog').addEventListener('click', function(e) {
        e.stopPropagation();
    });
});

// 测试代码（实际使用时可以移除）
// setTimeout(() => showError("数据加载失败，请稍后重试", "/data-report"), 1000); 3508.87

document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const userAvatar = document.getElementById('userAvatar');
    const avatarMenu = document.getElementById('avatarMenu');
    const changeAvatarBtn = document.getElementById('changeAvatarBtn');
    const viewProfileBtn = document.getElementById('viewProfileBtn');
    const avatarModal = document.getElementById('avatarModal');
    const cancelChangeBtn = document.getElementById('cancelChangeBtn');
    const confirmChangeBtn = document.getElementById('confirmChangeBtn');
    const fileInput = document.getElementById('fileInput');
    const previewImage = document.getElementById('previewImage');
    const defaultPreview = document.getElementById('defaultPreview');
    const logoutBtn = document.getElementById('logoutBtn');

    let selectedFile = null;

    // 获取用户信息
    fetch('/api/welcome-info')
        .then(response => response.json())
        .then(data => {
            if(data.code === 1) {
                // 更新基本信息
                document.getElementById('userNick').textContent = data.data.UserNick || '用户';
                document.getElementById('daysCount').textContent = data.data.DaysCount || '0';

                // 更新悬浮框详细信息
                document.getElementById('detailAccount').textContent = data.data.UserName || '未设置';
                document.getElementById('detailPassword').textContent = data.data.UserPwd || '已加密';
                document.getElementById('detailNick').textContent = data.data.UserNick || '未设置';
                document.getElementById('detailRegDate').textContent = data.data.DetailRegDate || '未知';
                document.getElementById('detailRole').textContent = data.data.UserBalance || '0';

                // 更新头像
                if(data.data.UserAvatar) {
                    document.getElementById('userAvatar').src =data.data.UserAvatar;
                }
            }
        })
        .catch(error => {
            console.error('获取用户信息失败:', error);
            document.getElementById('userNick').textContent = '用户';
        });

    // 点击头像显示/隐藏菜单
    userAvatar.addEventListener('click', function(e) {
        e.stopPropagation();
        avatarMenu.classList.toggle('show');
    });

    // 点击其他地方隐藏菜单
    document.addEventListener('click', function() {
        avatarMenu.classList.remove('show');
    });

    // 阻止菜单点击事件冒泡
    avatarMenu.addEventListener('click', function(e) {
        e.stopPropagation();
    });

    // 点击更换头像按钮
    changeAvatarBtn.addEventListener('click', function() {
        avatarMenu.classList.remove('show');
        avatarModal.classList.add('show');
    });

    // 点击查看资料按钮
    viewProfileBtn.addEventListener('click', function() {
        avatarMenu.classList.remove('show');
        window.location.href = '/userinfo';
    });

    // 取消更换头像
    cancelChangeBtn.addEventListener('click', function() {
        avatarModal.classList.remove('show');
        resetFileInput();
    });

    // 选择文件
    fileInput.addEventListener('change', function(e) {
        if (e.target.files && e.target.files[0]) {
            selectedFile = e.target.files[0];

            // 验证文件类型和大小
            if (!selectedFile.type.startsWith('image/')) {
                alert('请选择图片文件');
                return resetFileInput();
            }

            if (selectedFile.size > 5 * 1024 * 1024) {
                alert('图片大小不能超过5MB');
                return resetFileInput();
            }

            // 显示预览
            const reader = new FileReader();
            reader.onload = function(event) {
                previewImage.src = event.target.result;
                previewImage.style.display = 'block';
                defaultPreview.style.display = 'none';
                confirmChangeBtn.disabled = false;
            };
            reader.readAsDataURL(selectedFile);
        }
    });

    // 确认更换头像
    confirmChangeBtn.addEventListener('click', function() {
        if (!selectedFile) return;

        // 这里添加实际上传逻辑
        const formData = new FormData();
        formData.append('avatar', selectedFile);

        fetch('/api/upload-avatar', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 1) {
                    // 更新头像显示
                    userAvatar.src = data.data;
                    avatarModal.classList.remove('show');
                    resetFileInput();
                    alert('头像更换成功');
                } else {
                    alert(data.message || '头像更换失败');
                }
            })
            .catch(error => {
                console.error('上传失败:', error);
                alert('上传失败，请重试');
            });
    });

    // 退出登录功能
    logoutBtn.addEventListener('click', function() {
        if (confirm("确定退出？")){
            // 发送退出请求
            fetch('/api/logout', {
                method: 'POST',
                credentials: 'include'
            })
                .then(() => {
                    // 清除所有Cookie
                    document.cookie.split(';').forEach(cookie => {
                        const [name] = cookie.trim().split('=');
                        document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
                    });

                    // 清除localStorage和sessionStorage（可选）
                    localStorage.clear();
                    sessionStorage.clear();
                    window.location.href = '/login_page';
                })
                .catch(error => {
                    console.error('退出失败:', error);
                    window.location.href = '/login_page';
                });
        }
    });

    // 重置文件输入
    function resetFileInput() {
        fileInput.value = '';
        previewImage.src = '';
        previewImage.style.display = 'none';
        defaultPreview.style.display = 'flex';
        confirmChangeBtn.disabled = true;
        selectedFile = null;
    }
});
